package com.finance.util.export;

import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.*;
import java.util.regex.Pattern;


/**
 * Created by ljg on 2017/4/10.
 */
public class ImportUtil<T> {
    protected final static Logger logger = LoggerFactory.getLogger(ImportUtil.class);

    private XSSFSheet sheet;

    private ImportUtil() {
    }
    public static ImportUtil getImportFactory(InputStream inputStream) {
        ImportUtil importUtil = null;
        try {
            importUtil = new ImportUtil();
            importUtil.sheet = new XSSFWorkbook(inputStream).getSheetAt(0);

        } catch (IOException e) {
            logger.error("导入解析异常", e);
        }
        return importUtil;
    }

    public List<T> outResult(Class<T> tClass) throws IllegalAccessException, InstantiationException, NoSuchFieldException {
        Map<String,String> headMap = new HashMap<String, String>();
        Field[] fields = tClass.getDeclaredFields();
        for (Field field : fields){
            ExcelHead excelHead = field.getAnnotation(ExcelHead.class);
            if(excelHead != null){
                headMap.put(excelHead.name(),field.getName());
            }
        }
        List<T> tList = new ArrayList<T>();

        Iterator<Row> iterator = sheet.iterator();
        Row row = iterator.next();
        Map<Integer,String> headNames = doWithRow(row);
        while (iterator.hasNext()){
            row = iterator.next();
            Map<Integer,String>values=doWithRow(row);
            T t = tClass.newInstance();
            for (Integer colIndex : headNames.keySet()){
                String headName = headNames.get(colIndex);
                String value = values.get(colIndex);
                reflectObject(t,headMap.get(headName),value);

            }
            tList.add(t);
        }
        return tList;
    }

    private void reflectObject(T t,String fieldName,String value) throws IllegalAccessException, InstantiationException, NoSuchFieldException {
        Field field=t.getClass().getDeclaredField(fieldName);
        field.setAccessible(true);
        field.set(t,value);
    }

    private Map<Integer,String> doWithRow(Row row){
        Pattern pattern = Pattern.compile("^\\-?[0-9]+(\\.[0-9]*)?$");
        DecimalFormat decimalFormat =  new DecimalFormat("0.00");
        Map<Integer,String> rowMap = new HashMap<Integer, String>();
        Iterator<Cell> cellIterator = row.iterator();
        while (cellIterator.hasNext()){
            Cell cell = cellIterator.next();
            cell.setCellType(Cell.CELL_TYPE_STRING);
            String value =cell.getStringCellValue();
            if(StringUtils.isNotBlank(value) && pattern.matcher(value).matches()){
                if (value.contains(".")){
                    value = decimalFormat.format(new BigDecimal(value));
                }
            }
            rowMap.put(cell.getColumnIndex(),value);
        }
        return rowMap;
    }

}